package com.etc.controller;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import com.etc.dto.Result;
import com.etc.entity.Customer;
import com.etc.entity.Discuss;
import com.etc.entity.Games;
import com.etc.entity.OrderMsg;
import com.etc.entity.PageInfo;
import com.etc.service.AdminService;
import com.etc.service.CustomerService;
import com.etc.service.impl.AdminServiceImpl;
import com.etc.service.impl.CustomerServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;

@WebServlet("/CustomerServlet")
public class CustomerServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private CustomerService CustomerService =new CustomerServiceImpl();
	private AdminService adminService = new AdminServiceImpl();
	private CustomerService customerService= new CustomerServiceImpl();
	
	
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// 接收请求参数
		String op = request.getParameter("op");
		// 通过op区分不同的请求
		if ("find".equals(op)) {// 佳隆
			// 调用查询方法
			serachCustomer(request, response);
		}else if("order".equals(op)) {
			order(request, response);
		}
		else if("unpaid".equals(op)) {
			unpaid(request, response);
		}else if("shoucang".equals(op)) {
			shoucang(request, response);
		}else if("del".equals(op)) {
			del(request, response);
		}else if ("xiugai".equals(op)) {
			// 调用查询方法
			xiugai(request, response);
		}else if ("pjsd".equals(op)) {
			// 调用查询方法
			pjsd(request, response);
		}else if ("comment".equals(op)) {
			// 调用查询方法
			comment(request, response);
		}
		else if ("chaoshi".equals(op)) {
			// 调用查询方法
			chaoshi(request, response);
		}
		
		// 姜南
		if("findCustomerByPage".equals(op)) {
			doGetCustomerListByPage(request,response);
		}else if("deleteCustomerById".equals(op)) {
			deleteCustomerById(request,response);
		}else if("addCustomer".equals(op)) {
			addCustomer(request,response);
		}else if("updateCustomer".equals(op)) {
			updateCustomer(request,response);
		}else if("findById".equals(op)) {
			doGetCustomerById(request,response);
		}
		
		if ("find2".equals(op)) {
			//调用查询方法
			doGetCustomerList(request, response);
		} 
	}
	//yiyao
	private void doGetCustomerList(HttpServletRequest request, HttpServletResponse response) 
			throws IOException,ServletException{
		Result result =new Result();
		// 接收请求参数
		String customernickname =request.getParameter("customernickname");
		String customermobile = request.getParameter("customermobile");
		Boolean flag2 = false;
		//调度，调用业务层
		
	if (customernickname == null ||"".equals(customernickname.trim())) {
		//表示请求没有传递必须参数
		//响应
		result.fail(0, "参数有误");
		return;
	}else {
		Customer customer =customerService.findCustomerByNickname(customernickname);

		if (customer != null) {
			result.fail(0, "昵称已存在");
			flag2 = false;
			//设置响应内容类型
			response.setContentType("application/json;charset=utf-8");
			//利用第三方类库将Result对象转换成JSON字符串，
			ObjectMapper objectMapper = new ObjectMapper();
			String json=objectMapper.writeValueAsString(result);
			response.getWriter().write(json);
			return;
		}else {
			if (customermobile == null ||"".equals(customermobile.trim())) {
				//表示请求没有传递必须参数
				//响应
				
				return;
			}else {
				customer =customerService.findCustomerByMobile(customermobile);
				if (customer != null) {
					result.fail(0, "手机号已存在");
					//设置响应内容类型
					response.setContentType("application/json;charset=utf-8");
					//利用第三方类库将Result对象转换成JSON字符串，
					ObjectMapper objectMapper = new ObjectMapper();
					String json=objectMapper.writeValueAsString(result);
					response.getWriter().write(json);
					return;
				}else {
					flag2 = true;
				}
			}		
		}

				
	}
	
	if(flag2) {
	
		//接受参数
		String  nickname =request.getParameter("customernickname");
		String  mobile =request.getParameter("customermobile");
		String  password =request.getParameter("customerpassword");
		String  status = "1";
		//构建用户对象
		Customer customer=new Customer();
		customer.setNickname(nickname);
		customer.setMobile(mobile);
		customer.setPassword(password);
		customer.setStatus(status==null?0:1);
		
		//调用业务层
		boolean flag =customerService.addCustomer(customer);
		if (flag) {
			//添加成功
			result.ok(flag);
		}else {
			//添加失败
			result.fail(0, "添加用户失败");
		}
		
		//设置响应内容类型
		response.setContentType("application/json;charset=utf-8");
		//利用第三方类库将Result对象转换成JSON字符串，
		ObjectMapper objectMapper = new ObjectMapper();
		String json=objectMapper.writeValueAsString(result);
		response.getWriter().write(json);
	}
	
			
	}
	
	
	// 佳隆
	private void chaoshi(HttpServletRequest request, HttpServletResponse response)  throws IOException, ServletException{
		int id=1; //从前端传一个顾客编号id
		int status=2;
		Customer customer=	CustomerService.search(id);	
		List<OrderMsg> orderMsg=	 CustomerService.searchOrderChao(id,status);
		for(int i=0;i<orderMsg.size();i++) {
			orderMsg.get(i).setNickname(customer.getNickname());
		}
		
		request.setAttribute("orderMsg", orderMsg);
		request.getRequestDispatcher("/front/wddd.jsp").forward(request, response);
		
	}
			private void comment(HttpServletRequest request, HttpServletResponse response)  throws IOException, ServletException{
			
			//System.out.println(1);
				int id=1;//从前端传一个顾客编号id
				List<Discuss>  discusses=CustomerService.searchDiscuss(id);
				
				request.setAttribute("discusses", discusses);
				request.getRequestDispatcher("/front/zixun.jsp").forward(request, response);
			}
	
	private void pjsd(HttpServletRequest request, HttpServletResponse response)  throws IOException, ServletException{
		//System.out.println(1);
		int id=1;//从前端传一个顾客编号id
		List<Games>  games=CustomerService.searchGames(id);
	
		request.setAttribute("games", games);
		request.getRequestDispatcher("/front/pjsd.jsp").forward(request, response);
		
	}

private void xiugai(HttpServletRequest request, HttpServletResponse response)  throws IOException, ServletException{
		
		request.getRequestDispatcher("/front/xgmm.jsp").forward(request, response);	
		
	}
	private void del(HttpServletRequest request, HttpServletResponse response)  throws IOException, ServletException{
		//	System.out.println(1);
		String id=	request.getParameter("id");
		//	System.out.println(id);
		int id1=Integer.parseInt(id);
		CustomerService.del(id1);
		response.sendRedirect("about?op=shoucang");
		
		}
	private void shoucang(HttpServletRequest request, HttpServletResponse response)  throws IOException, ServletException{
		//System.out.println(1);
		int id=1; //从前端传一个顾客编号id
		List<Games>  games=CustomerService.searchGames(id);
		request.setAttribute("games", games);
		request.getRequestDispatcher("/front/wdsc.jsp").forward(request, response);
	}
	
	private void unpaid(HttpServletRequest request, HttpServletResponse response)  throws IOException, ServletException{
		//	System.out.println(1);
			int id=1; //从前端传一个顾客编号id
			int status=0;
			Customer customer=	CustomerService.search(id);	
			List<OrderMsg> orderMsg=	 CustomerService.searchOrder(id,status);
			for(int i=0;i<orderMsg.size();i++) {
				orderMsg.get(i).setNickname(customer.getNickname());
			}
			
			request.setAttribute("orderMsg", orderMsg);
			request.getRequestDispatcher("/front/wddd.jsp").forward(request, response);
			
			
		}
	private void order(HttpServletRequest request, HttpServletResponse response)  throws IOException, ServletException{
		//	System.out.println(1);
			int id=1; //从前端传一个顾客编号id
			int status=1;
			Customer customer=	CustomerService.search(id);
			
			List<OrderMsg> orderMsg=	 CustomerService.searchOrder(id,status);
			for(int i=0;i<orderMsg.size();i++) {
				orderMsg.get(i).setNickname(customer.getNickname());
			}
			
			request.setAttribute("orderMsg", orderMsg);
			request.getRequestDispatcher("/front/wddd.jsp").forward(request, response);
			
			
		}
		private void serachCustomer(HttpServletRequest request, HttpServletResponse response)  throws IOException, ServletException{
		//System.out.println(1);
			int id=1;//这里从前端获取当前的用户id
			
		Customer customer=	CustomerService.search(id);
		request.setAttribute("cumtomer", customer);
		request.getRequestDispatcher("/front/grxx.jsp").forward(request, response);
		
		//System.out.println(customer);
		}
		
		// 姜南
		private void doGetCustomerById(HttpServletRequest request, HttpServletResponse response) throws IOException {
			// TODO Auto-generated method stub
			Result<Customer> result = new Result<Customer>();
			//接受请求参数
			String customerId = request.getParameter("customerId");
			//对参数进行校验中
			if(customerId == null) {
				result.fail(0, "参数错误");
			}else {
				//
				Customer customer = adminService.getCustomerById(Integer.parseInt(customerId));
				result.ok(customer);
			}
			response.setContentType("application/json;charset=utf-8");
			ObjectMapper objectMapper = new ObjectMapper();
			String json = objectMapper.writeValueAsString(result);
			response.getWriter().write(json);
			
		}

		private void updateCustomer(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
			// TODO Auto-generated method stub
			// 响应统一格式对象
			Result<Boolean> result = new Result<Boolean>();
			
			// 接收参数
			String customerId = request.getParameter("customerId");
			String nickname = request.getParameter("nickname"); // 修改必须获取商品编号
			String mobile = request.getParameter("mobile");
			String password = request.getParameter("password");
			String status = request.getParameter("status"); // on
			Part part = request.getPart("imageFile"); // 文件
			
			// 构建用户对象
			Customer customer = new Customer();
			customer.setCustomerId(Integer.parseInt(customerId));
			customer.setNickname(nickname);
			customer.setMobile(mobile);
			customer.setPassword(password);
			customer.setStatus(status == null ? 0 : 1);
		
			// 标记上传的文件是否有问题
			boolean fileError = false;// 默认无问题

			// 判断是否有上传文件
			if (part.getSize() != 0) {

				// 对文件格式进行校验:内容类型,文件大小
				// 获取文件内容类型
				String contentType = part.getContentType(); // image/jpg
				// 限制文件类型
				String allowImageContentType = "image/png,image/jpeg,image/jpg";

				// 校验文件类型和大小
				if (allowImageContentType.indexOf(contentType) == -1) {
					// 设置标记
					fileError = true;
					// 响应结果:文件类型不合法
					result.fail(0, "文件类型不匹配,只能支持image/png,image/jpeg,image/jpg");
				} else if (part.getSize() > 200000) {
					// 设置标记
					fileError = true;
					// 响应结果:文件大小不合法
					result.fail(0, "文件大小不合法,不能超过200000字节");
				} else {
					// 合法文件

					// 获取文件真实名
					String fileName = part.getSubmittedFileName();// demo.jpg
					// 获取文件扩展名
					String fileSuffix = fileName.substring(fileName.lastIndexOf(".")); // .jpg

					// 定义存储文件名,保证唯一
					// 时间戳14+4位随机数+原文件名
					StringBuffer writeFileName = new StringBuffer();
					// 时间戳
					LocalDateTime ldt = LocalDateTime.now();
					DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
					String dateTime = dtf.format(ldt);
					// 随机数4位 0000-9999
					int a = (int) (Math.random() * 10);// [0,9]
					int b = (int) (Math.random() * 10);// [0,9]
					int c = (int) (Math.random() * 10);// [0,9]
					int d = (int) (Math.random() * 10);// [0,9]
					// 拼接存储的文件名
					// 不保留真实文件名,最终以时间戳+随机数存储
					writeFileName.append(dateTime).append(a).append(b).append(c).append(d).append(fileSuffix); // 202112101723251458.jpg

					// 存储文件
					// File类关联存储文件的目录
					File file = new File("C:\\upload\\image");

					// 定义文件完整路径
					StringBuffer filePath = new StringBuffer();
					filePath.append(file).append(File.separator).append(writeFileName); // C:\\upload\\image\\202112101723251458.jpg

					// 将文件写入指定服务器位置
					part.write(filePath.toString());

					// 有上传文件,数据库中存储文件名
					customer.setImage(writeFileName.toString());
				}

			} else {
				// 没有上传文件,使用默认图片,存储默认图片的文件名
				customer.setImage("NoPicture.jpg");
			}

			if (!fileError) {
				// 当上传文件没有问题,才有必要去调用业务层
				// 调用业务层
				Boolean flag = adminService.updateCustomer(customer);

				if (flag) {
					// 修改成功
					result.ok(flag);
				} else {
					// 修改失败
					result.fail(0, "修改商品出错");
				}
			}
			
			response.setContentType("application/json;charset=utf-8");
			ObjectMapper objectMapper = new ObjectMapper();
			String json = objectMapper.writeValueAsString(result);
			response.getWriter().write(json);
			
		
	}



		private void addCustomer(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
			// 响应统一格式对象
			Result<Boolean> result = new Result<Boolean>();

			// 接收参数
			String nickname = request.getParameter("nickname"); // 修改必须获取商品编号
			String mobile = request.getParameter("mobile");
			String password = request.getParameter("password");
			String status = request.getParameter("status"); // on
			Part part = request.getPart("imageFile"); // 文件
			String yulan = request.getParameter("yulan");
			Boolean flag1 = true;
			boolean flag2 = true;
			
			List<Customer> list = adminService.getCustomersList();
			for (Customer customer : list) {
				if(nickname.equals(customer.getNickname())) {
					result.fail(0, "用户昵称已存在");
					flag2 = false;
					response.setContentType("application/json;charset=utf-8");
					ObjectMapper objectMapper = new ObjectMapper();
					String json = objectMapper.writeValueAsString(result);
					response.getWriter().write(json);
					
				}else if(mobile.equals(customer.getMobile())) {
					result.fail(0, "用户手机号已存在");
					flag2 = false;
					response.setContentType("application/json;charset=utf-8");
					ObjectMapper objectMapper = new ObjectMapper();
					String json = objectMapper.writeValueAsString(result);
					response.getWriter().write(json);
				}
			}
			
			
			if(flag2){
					// 构建用户对象
					Customer customer = new Customer();
					customer.setNickname(nickname);
					customer.setMobile(mobile);
					customer.setPassword(password);
					customer.setStatus(status == null ? 0 : 1);
				
					// 标记上传的文件是否有问题
					boolean fileError = false;// 默认无问题
					if(yulan != null)
					{
						flag1 = false;
					}
					
					// 判断是否有上传文件
					if (part.getSize() != 0) {

						// 对文件格式进行校验:内容类型,文件大小
						// 获取文件内容类型
						String contentType = part.getContentType(); // image/jpg
						// 限制文件类型
						String allowImageContentType = "image/png,image/jpeg,image/jpg";

						// 校验文件类型和大小
						if (allowImageContentType.indexOf(contentType) == -1) {
							// 设置标记
							fileError = true;
							// 响应结果:文件类型不合法
							result.fail(0, "文件类型不匹配,只能支持image/png,image/jpeg,image/jpg");
						} else if (part.getSize() > 200000) {
							// 设置标记
							fileError = true;
							// 响应结果:文件大小不合法
							result.fail(0, "文件大小不合法,不能超过200000字节");
						} else {
							// 合法文件

							// 获取文件真实名
							String fileName = part.getSubmittedFileName();// demo.jpg
							// 获取文件扩展名
							String fileSuffix = fileName.substring(fileName.lastIndexOf(".")); // .jpg

							// 定义存储文件名,保证唯一
							// 时间戳14+4位随机数+原文件名
							StringBuffer writeFileName = new StringBuffer();
							// 时间戳
							LocalDateTime ldt = LocalDateTime.now();
							DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
							String dateTime = dtf.format(ldt);
							// 随机数4位 0000-9999
							int a = (int) (Math.random() * 10);// [0,9]
							int b = (int) (Math.random() * 10);// [0,9]
							int c = (int) (Math.random() * 10);// [0,9]
							int d = (int) (Math.random() * 10);// [0,9]
							// 拼接存储的文件名
							// 不保留真实文件名,最终以时间戳+随机数存储
							writeFileName.append(dateTime).append(a).append(b).append(c).append(d).append(fileSuffix); // 202112101723251458.jpg

							// 存储文件
							// File类关联存储文件的目录
							File file = new File("C:\\upload\\image");

							// 定义文件完整路径
							StringBuffer filePath = new StringBuffer();
							filePath.append(file).append(File.separator).append(writeFileName); // C:\\upload\\image\\202112101723251458.jpg

							// 将文件写入指定服务器位置
							part.write(filePath.toString());

							// 有上传文件,数据库中存储文件名
							customer.setImage(writeFileName.toString());
						}

					} else {
						// 没有上传文件,使用默认图片,存储默认图片的文件名
						if(flag1) {
							customer.setImage("NoPicture.jpg");
						}
						
					}

					if (!fileError) {
						// 当上传文件没有问题,才有必要去调用业务层
						// 调用业务层
						Boolean flag = adminService.addCustomer(customer);

						if (flag) {
							// 修改成功
							result.ok(flag);
						} else {
							// 修改失败
							result.fail(0, "添加商品出错");
						}
					}
					
					response.setContentType("application/json;charset=utf-8");
					ObjectMapper objectMapper = new ObjectMapper();
					String json = objectMapper.writeValueAsString(result);
					response.getWriter().write(json);
				}
				
			
			}
			
			
			
		

		private void deleteCustomerById(HttpServletRequest request, HttpServletResponse response) throws IOException {
			// TODO Auto-generated method stub
			//响应统一格式对象
			Result result = new Result();
			//接受请求参数
			String CustomerId = request.getParameter("CustomerId");
			
			//对参数进行校验
			if(CustomerId == null) {
				result.fail(0, "未获得参数");
			}else {
				//调用业务层
				Boolean flag = adminService.deleteCustomerById(Integer.parseInt(CustomerId));
				result.ok(flag);
			}
			//响应
			response.setContentType("appliction/json;charset=utf-8");
			ObjectMapper objectMapper = new ObjectMapper();
			String json = objectMapper.writeValueAsString(result);
			response.getWriter().write(json);
			
		}

		private void doGetCustomerListByPage(HttpServletRequest request, HttpServletResponse response) throws IOException {
			// TODO Auto-generated method stub
			//响应统一格式对象
			Result result = new Result();
			
			//接受请求参数
			String nickNameKeyWord = request.getParameter("nickNameKeyWord");
			String pageNum = request.getParameter("pageNum");
			String pageSize = request.getParameter("pageSize");
			
			//对参数进行校验
			if(pageNum==null || pageSize==null) {
				result.fail(0, "参数错误");
			}else {
				//调用业务层
				PageInfo<Customer> pageInfo = adminService.getCustomerListByPage(nickNameKeyWord,Integer.parseInt(pageNum), Integer.parseInt(pageSize));
				result.ok(pageInfo);
			}
			
			//响应
			response.setContentType("appliction/json;charset=utf-8");
			ObjectMapper objectMapper = new ObjectMapper();
			String json = objectMapper.writeValueAsString(result);
			response.getWriter().write(json);
			
		}
	
	
}
